//
//  JDBaseViewController.swift
//  DragonWallet
//
//  Created by volantPig on 2024/2/6.
//

import UIKit
import SnapKit
import JGProgressHUD
import AVFoundation
import SwiftEntryKit

typealias PictureSelectedCompleted = (UIImage) -> Void
typealias VideoSelectedCompleted = (String, UIImage?) -> Void
typealias OnePickerViewCompleted = (Int) -> Void

class JDBaseViewController: UIViewController {
    
    var customNavigationBar: UINavigationBar?
    lazy var customTopItem: UINavigationItem = {
        let item = UINavigationItem()
        return item
    }()
    
    var selectedVideoCompleted: ((UIImage?,String?)->())?
    var caremaPhotoCompleted: ((AblumType,[UIImage])->())?
    
    // MARK: HXPhotoPickerViewControler
    /// 相关配置
    // MARK: HXPhotoPickerViewControler
    
    
    
    var simpleCallBack: (()->())?
    let commonColor = color("#F5F6F8")
    
    var pickerViewBgView: UIView?
    var pickerViewConfirmButton: UIButton?
    var pickerViewCancelButton: UIButton?
    var pickerViewTitleLabel: UILabel?
    var pickerViewTopToolBar: UIView?
    /// 单项pickerView
    var onePickerView: UIPickerView?
    var onePickerViewDataSource = [String]()
    var onePickerViewCompleted: OnePickerViewCompleted?
    var pictureSelectedCompleted :PictureSelectedCompleted?
    var videoSelectedCompleted: VideoSelectedCompleted?
    
    
    
    var currentPage = 1
    
    /// 当前经度
    var currentLongitude: Double?
    /// 当前纬度
    var currentLatitude: Double?
    
    var loading = JGProgressHUD(style: .dark)
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = .init(hexString: "#F5F6F8")
        self.navigationController?.navigationBar.isTranslucent = false
        
        // MARK: 修改【状态栏】和【导航栏】的颜色
//        self.navigationController?.navigationBar.backgroundColor = self.commonColor
//        self.customStatusBarBackgroundColor(self.commonColor)
        
        self.setupNavigationBarConfig()
        self.customNewNavigationBar()
        
        self.addObservers()
        // Do any additional setup after loading the view.
    }
    
    func addObservers() {
        NotificationCenter.default.addObserver(self, selector: #selector(getNetData(_:)), name: NSNotification.Name("LoginRefresh"), object: nil)
    }
    
    @objc func getNetData(_ isRefresh: Bool = true) {}
    
    @objc func backAction() {
        self.navigationController?.popViewController(animated: true)
    }
    
//    func customStatusBarBackgroundColor(_ customColor: UIColor) {
//        for subV in self.navigationController?.navigationBar.subviews ?? [UIView]() {
//            if subV.tag == 10086 {
//                subV.removeFromSuperview()
//                break
//            }
//        }
//        
//        let stateView = UIView(frame: CGRectMake(0, -(UIDevice().safeAreaInset.top-44), screenWidth, UIDevice().safeAreaInset.top-44))
//        stateView.tag = 10086
//        stateView.backgroundColor = customColor
//        self.navigationController?.navigationBar.addSubview(stateView)
//    }
    
//
//    func customTextRightBarButtonItem(_ buttonTitle: String,_ action: Selector,_ target: Any?) {
//        
//        let titleLabel = UILabel()
//        titleLabel.text = buttonTitle
//        let width = buttonTitle.boundingRect(with: CGSize(width: CGFloat(MAXFLOAT), height: 44), options: .usesLineFragmentOrigin, attributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 13, weight: .regular)], context: nil).size.width+20
//        titleLabel.frame = CGRectMake(0, 0, width, 44)
//        titleLabel.labelConfig(textAlignment: .right, font: UIFont.systemFont(ofSize: 13, weight: .regular), textColor: color("#FF3E2F"))
//        titleLabel.backgroundColor = .commonColor()
//        
////        let rightControl = UIControl(frame: CGRectMake(0, 0, width, 44))
////        titleLabel.addSubview(rightControl)
////        rightControl.addTarget(target, action: action, for: .touchUpInside)
////        rightControl.backgroundColor = .green
//        
//        let rightBarButtonItem = UIBarButtonItem(image: JDTools.convertUIViewToUIImage(view: titleLabel).withRenderingMode(.alwaysOriginal), style: .plain, target: target, action: action)
//        rightBarButtonItem.customView?.backgroundColor = .commonColor()
//        
////        UIBarButtonItem(customView: titleLabel)
////        JDTools.convertUIViewToUIImage(view: titleLabel)
//        
//        self.navigationItem.rightBarButtonItem = rightBarButtonItem
//    }
//    
//    func customLeftBarButtonItem(_ imageName: String,_ action: Selector,  _ target: Any?) {
//        
//        let leftBarButtonItem = UIBarButtonItem(image: UIImage(named: imageName)?.withRenderingMode(.alwaysOriginal), style: .plain, target: target, action: action)
//        
//        self.navigationItem.leftBarButtonItem = leftBarButtonItem
//    }
//    
//    
    func customRightImageButton(_ buttonTitleStr: String = "发布", _ action: Selector) {
        
        let containerView = UIView(frame: .init(x: 0, y: 0, width: 70, height: 34))
        containerView.layer.cornerRadius = 17
        containerView.backgroundColor = .white
        
        let imageV = UIImageView()
        containerView.addSubview(imageV)
        imageV.frame = CGRect(x: 11, y: 10.5, width: 13, height: 13)
        imageV.image = UIImage(named: "sendImgV")?.withRenderingMode(.alwaysOriginal)
        imageV.contentMode = .scaleAspectFit
        
        let buttonTitle = UILabel()
        containerView.addSubview(buttonTitle)
        buttonTitle.frame = CGRect(x: 29, y: 0, width: 40, height: 34)
        buttonTitle.text = buttonTitleStr
        buttonTitle.labelConfig(textAlignment: .center, font: .systemFont(ofSize: 14, weight: .regular), textColor: color("#333333"))
        buttonTitle.isUserInteractionEnabled = false
        
        let control = UIControl(frame: .init(x: 0, y: 0, width: 70, height: 34))
        control.addTarget(self, action: action, for: .touchUpInside)
        containerView.addSubview(control)
        
        let rightBarButtonItem = UIBarButtonItem(customView: containerView)
        self.customTopItem.rightBarButtonItem = rightBarButtonItem
        
    }
//    
//    
//    func customRightBarButtonItems(_ imageNames: [String],_ actions: [Selector], _ target: Any?, _ space: Int = 0) {
//        
//        let maxNumber = imageNames.count > actions.count ? actions.count : imageNames.count
//        
//        let bgView = UIView()
//        bgView.frame = CGRectMake(0, 0, CGFloat(maxNumber*(36+space)-space), 44)
//        
//        for index in 0..<maxNumber {
//            
//            let button = UIButton(type: .custom)
//            bgView.addSubview(button)
//            button.frame = CGRect(x: index*(36+space), y: 0, width: 36, height: 44)
//            button.addTarget(target, action: actions[index], for: .touchUpInside)
//            button.setImage(UIImage(named: imageNames[index])?.withRenderingMode(.alwaysOriginal), for: .normal)
//            button.imageView?.contentMode = .scaleAspectFit
//        }
//        
//        let rightBarButtonItem = UIBarButtonItem(customView: bgView)
//        self.navigationItem.rightBarButtonItem = rightBarButtonItem
//        
//    }
//    
//    func customSmallRightBarButtonItems(_ imageNames: [String],_ actions: [Selector], _ target: Any?) {
//        
//        let maxNumber = imageNames.count > actions.count ? actions.count : imageNames.count
//        
//        let bgView = UIView()
//        bgView.frame = CGRectMake(0, 0, CGFloat(maxNumber*30), 44)
//        
//        for index in 0..<maxNumber {
//            
//            let button = UIButton(type: .custom)
//            bgView.addSubview(button)
//            button.frame = CGRect(x: index*30, y: 0, width: 16, height: 44)
//            button.addTarget(target, action: actions[index], for: .touchUpInside)
//            button.setImage(UIImage(named: imageNames[index])?.withRenderingMode(.alwaysOriginal), for: .normal)
//            button.imageView?.contentMode = .scaleAspectFit
//        }
//        
//        let rightBarButtonItem = UIBarButtonItem(customView: bgView)
//        self.navigationItem.rightBarButtonItem = rightBarButtonItem
//        
//    }
//    
//    func clearRightBarButtonItem() {
//        self.navigationItem.rightBarButtonItem = nil
//    }
    
    
    /// 移除navigationBar底部 分割线
    func removeSeparatorLine() {
//        if let navigationBar = self.navigationController?.navigationBar {
//            for subView in navigationBar.subviews {
//                for subview1 in subView.subviews {
//                    if subview1.frame.size.height < 1 && subview1.frame.size.width > (screenWidth - 10) {
//                        subview1.isHidden = true
//                    }
//                }
//            }
//        }
        
        
        if let navigationBar = self.customNavigationBar {
            for subView in navigationBar.subviews {
                for subview1 in subView.subviews {
                    if subview1.frame.size.height < 1 && subview1.frame.size.width > (screenWidth - 10) {
                        subview1.isHidden = true
                    }
                }
            }
        }
    }
    
    func addSeparatorLine() {
        if let navigationBar = self.navigationController?.navigationBar {
            for subView in navigationBar.subviews {
                for subview1 in subView.subviews {
                    if subview1.frame.size.height < 1 && subview1.frame.size.width > (screenWidth - 10) {
                        subview1.isHidden = false
                    }
                }
            }
        }
    }
    
    
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */
    
    func showLoading() {
        self.loading.show(in: JDTools.getKeyWindows()?.rootViewController?.view ?? self.view)
    }
    
    func dismissLoading() {
        self.loading.dismiss()
    }
    
    func showConfirmView(_ hitStr: String?, _ callBack: (()->Void)?) {
        let popupConfirmView = JDPopupConfirmView()
        popupConfirmView.confirmButtonSelected = callBack
        popupConfirmView.titleStr = hitStr
        JDTools.getKeyWindows()?.rootViewController?.view.addSubview(popupConfirmView)
    }

    
    func changeNavigationBarAlpha(_ alpha: CGFloat) {
        for subView in self.navigationController?.navigationBar.subviews ?? [UIView]() {
            var bgView: UIView? = nil
            let className = NSStringFromClass(subView.classForCoder)
            if className.elementsEqual("_UINavigationBarBackground") || className.elementsEqual("UINavigationBarBackground") {
                bgView = subView
                break
            } else if className.elementsEqual("_UIBarBackground") {
                bgView = subView
                for sub in subView.subviews {
                    let subName = NSStringFromClass(sub.classForCoder)
                    if subName.elementsEqual("UIImageView") {
                        self.navigationController?.navigationBar.alpha = alpha
                        sub.alpha = alpha
                        break
                    }
                }
            }
        }
    }
}

// MARK: 图片选择器相关代理
extension JDBaseViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    // 选择图片
    func openImgagePickerVC() {
        
        let imagePickerController = UIImagePickerController()
        imagePickerController.delegate = self
        let alertVC = UIAlertController(title: "请选择上传方式", message: "", preferredStyle: .actionSheet)
        
        let albumAction = UIAlertAction(title: "相册", style: .default) {[weak self] _ in
            imagePickerController.sourceType = .photoLibrary
            self?.present(imagePickerController, animated: true)
        }
        
        let cameraAction = UIAlertAction(title: "相机", style: .default) {[weak self] _ in
            imagePickerController.sourceType = .camera
            self?.present(imagePickerController, animated: true)
        }
        
        let cancelAction = UIAlertAction(title: "取消", style: .cancel) { _ in
            
        }
        alertVC.addAction(albumAction)
        alertVC.addAction(cameraAction)
        alertVC.addAction(cancelAction)
        alertVC.modalPresentationStyle = .fullScreen
        self.present(alertVC, animated: true)
    }
    
    /// 选择视频
    func selectedVideo() {
        
        let alertVC = UIAlertController(title: "请选择上传方式", message: "", preferredStyle: .actionSheet)
        
        let albumAction = UIAlertAction(title: "录像", style: .default) {[weak self] _ in
            self?.startVideo()
        }
        
        let cameraAction = UIAlertAction(title: "本地视频", style: .default) {[weak self] _ in
            self?.chooseVide()
        }
        
        let cancelAction = UIAlertAction(title: "取消", style: .cancel) { _ in
            
        }
        alertVC.addAction(albumAction)
        alertVC.addAction(cameraAction)
        alertVC.addAction(cancelAction)
        alertVC.modalPresentationStyle = .fullScreen
        self.present(alertVC, animated: true)
    }
    
    // 打开相册选择视频
    func chooseVide() {
        let imagePickerController = UIImagePickerController()
        imagePickerController.sourceType = .photoLibrary
        let availableMedia = UIImagePickerController.availableMediaTypes(for: .camera)
        if (availableMedia?.count ?? 0) > 1 {
            if let mediaType = availableMedia?[1] {
                imagePickerController.mediaTypes = [mediaType]
            }
        }
        self.present(imagePickerController, animated: true)
        imagePickerController.delegate = self
    }
    
    // 打开相机录像
    func startVideo() {
        let imagePickerController = UIImagePickerController()
        imagePickerController.sourceType = .camera
        let availableMedia = UIImagePickerController.availableMediaTypes(for: .camera)
        if (availableMedia?.count ?? 0) > 1 {
            if let mediaType = availableMedia?[1] {
                imagePickerController.mediaTypes = [mediaType]
            }
        }
        self.present(imagePickerController, animated: true)
        imagePickerController.delegate = self
    }
    
    
    
    
    public func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        printLog("选择了图片")
        
        if let photoImage = info[UIImagePickerController.InfoKey.originalImage] as? UIImage {
            picker.dismiss(animated: true) {
                // 将图片放到对应位置
                self.caremaPhotoCompleted?(.photoCamera,[photoImage])
//                self.pictureSelectedCompleted?(photoImage)
            }
        }
        
        if let videoUrl = info[UIImagePickerController.InfoKey.mediaURL] as? URL {
            
            if videoUrl.path.contains("PluginKitPlugin") {
                // 13以后的本地路径
                if let videoName = videoUrl.path.components(separatedBy: "/").last {
                    let fileManager = FileManager.default
                    let documentsDirectory = NSHomeDirectory() + "/" + "Documents"
                    if !fileManager.fileExists(atPath: documentsDirectory) {
                        try? fileManager.createDirectory(atPath: documentsDirectory, withIntermediateDirectories:true)
                    }
                    let newFilePath = documentsDirectory + "/" + videoName
                    do {
                        try fileManager.copyItem(at: videoUrl, to: URL.init(fileURLWithPath: newFilePath))
                        picker.dismiss(animated: true) {
                            // 将图片放到对应位置
                            // 还需要一个首帧图片
                            self.videoSelectedCompleted?(newFilePath,JDTools.getVideoThumbnail(url: URL.init(fileURLWithPath: newFilePath)))
                        }
                    } catch {
                        printLog("本地视频处理异常")
                    }
                }
            } else {
                picker.dismiss(animated: true) {
                    // 将图片放到对应位置
                    self.videoSelectedCompleted?(videoUrl.path,JDTools.getVideoThumbnail(url: videoUrl))
                }
            }
        }
    }
    
}


// ↓↓↓↓↓↓↓↓↓↓ 获取首帧图片  ↓↓↓↓↓↓↓↓↓↓↓↓
//import AVFoundation
//


//// 使用方法
//if let videoURL = URL(string: "你的视频URL") {
//    if let thumbnailImage = getVideoThumbnail(url: videoURL) {
//        // 使用首帧图片
//        print("获取到的首帧图片: \(thumbnailImage)")
//    }
//}

// MARK: 导航栏处理
extension JDBaseViewController {
    /// 设置 navigationBar的配置信息
    func setupNavigationBarConfig() {
        let barApp = UINavigationBarAppearance()
        barApp.configureWithOpaqueBackground()
        barApp.backgroundColor = .clear
        barApp.titleTextAttributes = [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 16, weight: .semibold), NSAttributedString.Key.foregroundColor: UIColor.black]
        self.navigationController?.navigationBar.standardAppearance = barApp
        self.navigationController?.navigationBar.scrollEdgeAppearance = barApp
    }
    
    func customNewNavigationBar() {
        self.navigationController?.navigationBar.isHidden = true
        
        self.customNavigationBar = UINavigationBar(frame: CGRectMake(0, statusBarHeight, UIScreen.main.bounds.size.width, 44))
        self.customNavigationBar?.backgroundColor = .commonColor()
        self.view.addSubview(self.customNavigationBar!)
        self.customNavigationBar?.barTintColor = .commonColor()
        self.customNavigationBar?.tintColor = color("#FA6161")
        self.customNavigationBar?.titleTextAttributes = [.foregroundColor: UIColor.black]
        self.customNavigationBar?.isTranslucent = false
        
        self.customNavigationBar?.items = [self.customTopItem]
        
        self.customNavigationBar?.shadowImage = UIImage()
        
 
//        self.removeSeparatorLine()
        
    }
    
    func setupNavigationTitle(_ title: String) {
        self.customTopItem.title = title
    }
    
    func setupLeftBackItem() {
        let leftBarButtonItem = UIBarButtonItem(image: UIImage(named: "black_back")?.withRenderingMode(.alwaysOriginal), style: .plain, target: self, action: #selector(backAction))
        self.customTopItem.leftBarButtonItem = leftBarButtonItem
    }
    
    func setupBackTitle(_ titleStr: String) {
        let label = UILabel()
        self.customNavigationBar?.addSubview(label)
        label.snp.makeConstraints { make in
            make.centerY.equalTo(self.customNavigationBar!)
            make.leading.equalTo(self.customNavigationBar!).offset(44)
        }
        label.labelConfig(textAlignment: .left, font: UIFont.systemFont(ofSize: 18, weight: .semibold), textColor: color("#333333"), numberOfLines: 1)
        label.text = titleStr
        
    }
    
    // MARK: 这个方法，暂时不用
    func customBackBarButtonItem(_ action: Selector,_ target: Any?) {
        let backBarButtonItem = UIBarButtonItem(image: UIImage(named: "black_back"), style: .plain, target: target, action: action)
        self.customTopItem.leftBarButtonItem = backBarButtonItem
    }
    
    func customImageLeftBarButtonItem(_ imageName: String,_ action: Selector,  _ target: Any?) {
        let leftBarButtoItem = UIBarButtonItem(image: UIImage(named: imageName)?.withRenderingMode(.alwaysOriginal), style: .plain, target: target, action: action)
        self.customTopItem.leftBarButtonItem = leftBarButtoItem
    }
    
    func customImageRightBarButtonItem(_ imageName: String,_ action: Selector,  _ target: Any?) {
        let rightBarButtoItem = UIBarButtonItem(image: UIImage(named: imageName)?.withRenderingMode(.alwaysOriginal), style: .plain, target: target, action: action)
        self.customTopItem.rightBarButtonItem = rightBarButtoItem
    }
    
    func customTextLeftBarButtonItem(_ buttonTitle: String,_ action: Selector,  _ target: Any?) {
        let leftBarButtoItem = UIBarButtonItem(title: buttonTitle, style: .plain, target: target, action: action)
        self.customTopItem.leftBarButtonItem = leftBarButtoItem
    }
    
    func customTextRightBarButtonItem(_ buttonTitle: String,_ action: Selector,  _ target: Any?) {
        let rightBarButtoItem = UIBarButtonItem(title: buttonTitle, style: .plain, target: target, action: action)
        self.customTopItem.rightBarButtonItem = rightBarButtoItem
    }
    
    // MARK: 双按钮模式
    func customRightBarButtonItems(_ imageNames: [String],_ actions: [Selector], _ target: Any?, _ space: Int = 0) {
        let minNumber = imageNames.count > actions.count ? actions.count : imageNames.count
        
        let bgView = UIView()
        bgView.frame = CGRectMake(0, 0, CGFloat(minNumber*(36+space)-space), 44)
        for index in 0..<minNumber {
            
            let button = UIButton(type: .custom)
            bgView.addSubview(button)
            button.frame = CGRect(x: index*(36+space), y: 0, width: 36, height: 44)
            button.addTarget(target, action: actions[index], for: .touchUpInside)
            button.setImage(UIImage(named: imageNames[index])?.withRenderingMode(.alwaysOriginal), for: .normal)
            button.imageView?.contentMode = .scaleAspectFit
        }
        
        let rightBarButtonItem = UIBarButtonItem(customView: bgView)
        self.customTopItem.rightBarButtonItem = rightBarButtonItem
    }
    
    func customSmallRightBarButtonItems(_ imageNames: [String],_ actions: [Selector], _ target: Any?) {
        
        let minNumber = imageNames.count > actions.count ? actions.count : imageNames.count
        let bgView = UIView()
        bgView.frame = CGRectMake(0, 0, CGFloat(minNumber*30), 44)
        
        for index in 0..<minNumber {
            
            let button = UIButton(type: .custom)
            bgView.addSubview(button)
            button.frame = CGRect(x: index*30, y: 0, width: 16, height: 44)
            button.addTarget(target, action: actions[index], for: .touchUpInside)
            button.setImage(UIImage(named: imageNames[index])?.withRenderingMode(.alwaysOriginal), for: .normal)
            button.imageView?.contentMode = .scaleAspectFit
        }
        
        let rightBarButtonItem = UIBarButtonItem(customView: bgView)
        self.customTopItem.rightBarButtonItem = rightBarButtonItem
        
    }
    
    // MARK: 清除按钮
    func clearRightBarButtonItem() {
        self.customTopItem.rightBarButtonItem = nil
    }
    
    func changeTitleView(_ customView: UIView?) {
        self.customTopItem.titleView = customView
    }
    // MARK: 子控件分离
    
    func splitOnlyTitleNavigation( _ titleStr: String) {
        let titleLabel = UILabel()
        self.view.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { make in
            make.centerX.equalTo(self.customNavigationBar!)
            make.top.bottom.equalTo(self.customNavigationBar!)
        }
        titleLabel.labelConfig(textAlignment: .center, font: UIFont.systemFont(ofSize: 18, weight: .semibold), textColor: .white, numberOfLines: 1)
        titleLabel.text = titleStr
    }
    
    
    func splitSubviewNavigationbar(_ imageName: String, _ action: Selector, _ target: Any?, _ titleStr: String) {
        
        self.customNavigationBar?.items?.removeAll()
        
        let leftButton = UIButton(type: .custom)
        self.view.addSubview(leftButton)
        leftButton.snp.makeConstraints { make in
            make.leading.equalTo(self.view)//.offset(12)
            make.centerY.equalTo(self.customNavigationBar!)
            make.size.equalTo(CGSizeMake(44, 44))
        }
        leftButton.setImage(UIImage(named: imageName), for: .normal)
        leftButton.addTarget(target, action: action, for: .touchUpInside)

        let titleLabel = UILabel()
        self.view.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { make in
            make.centerX.equalTo(self.customNavigationBar!)
            make.top.bottom.equalTo(self.customNavigationBar!)
        }
        titleLabel.text = titleStr
    }
    
    func splitSubviewNavigationbar(_ leftImageName: String? = "",_ leftButtonStr: String? = "" ,_ leftButtonAction: Selector? = nil, _ rightImageName: String? = "",_ rightButtonStr: String? = "",_  rightButtonAction: Selector? = nil, _ target: Any? = nil, _ titleStr: String? = "",_ titleColor: UIColor? = .white) {

        self.customNavigationBar?.items?.removeAll()
        
        if (leftImageName?.count ?? 0) > 0 || (leftButtonStr?.count ?? 0) > 0 {
            let leftButton = UIButton(type: .custom)
            self.view.addSubview(leftButton)
            leftButton.snp.makeConstraints { make in
                make.leading.equalTo(self.view)//.offset(12)
                make.centerY.equalTo(self.customNavigationBar!)
                make.size.equalTo(CGSizeMake(44, 44))
            }
            if let imageName = leftImageName {
                leftButton.setImage(UIImage(named: imageName), for: .normal)
            }
            if let buttonTitle = leftButtonStr {
                leftButton.setTitle(buttonTitle, for: .normal)
            }
            if let action = leftButtonAction {
                leftButton.addTarget(target, action: action, for: .touchUpInside)
            }
            
//            if (leftImageName?.count ?? 0) > 0 && (leftButtonStr?.count ?? 0) > 0 {
//                leftButton.titleEdgeInsets = UIEdgeInsets.init(top: 0, left: 5, bottom: 0, right: 5)
//                leftButton.imageEdgeInsets = UIEdgeInsets.init(top: 0, left: 5, bottom: 0, right: 5)
//            }
        }
        
        if (rightImageName?.count ?? 0) > 0 || (rightButtonStr?.count ?? 0) > 0 {
            let rightButton = UIButton(type: .custom)
            self.view.addSubview(rightButton)
            rightButton.snp.makeConstraints { make in
                make.trailing.equalTo(self.view).offset(-16)
                make.centerY.equalTo(self.customNavigationBar!)
//                make.size.equalTo(CGSizeMake(44, 44))
            }
            if let imageName = rightImageName {
                rightButton.setImage(UIImage(named: imageName), for: .normal)
            }
            if let buttonTitle = rightButtonStr {
                rightButton.setTitle(buttonTitle, for: .normal)
                rightButton.titleLabel?.font = UIFont.systemFont(ofSize: 14, weight: .semibold)
                rightButton.setTitleColor(.white, for: .normal)
            }
            if let action = rightButtonAction {
                rightButton.addTarget(target, action: action, for: .touchUpInside)
            }
            
            if (rightImageName?.count ?? 0) > 0 && (rightButtonStr?.count ?? 0) > 0 {
                rightButton.titleEdgeInsets = UIEdgeInsets.init(top: 0, left: 5, bottom: 0, right: 5)
                rightButton.imageEdgeInsets = UIEdgeInsets.init(top: 0, left: 5, bottom: 0, right: 5)
            }
            
        }
        
        let titleLabel = UILabel()
        self.view.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { make in
            make.centerX.equalTo(self.customNavigationBar!)
            make.top.bottom.equalTo(self.customNavigationBar!)
        }
        titleLabel.text = titleStr
        titleLabel.textColor = titleColor
    }
    
    
    func splitNavigationbarCustomRightImageButton(_ rightImageName: String = "",_ rightButtonStr: String = "",_  rightButtonAction: Selector, _ target: Any? = nil, _ space: Int = 0) {
        
        let containerView = UIView()
        self.view.addSubview(containerView)
        containerView.snp.makeConstraints { make in
            make.trailing.equalTo(self.view).offset(-16)
            make.centerY.equalTo(self.customNavigationBar!)
            make.height.equalTo(44)
        }
        
        let buttonTitle = UILabel()
        containerView.addSubview(buttonTitle)
        buttonTitle.snp.makeConstraints { make in
            make.trailing.equalTo(containerView)
            make.centerY.equalTo(containerView)
        }
        buttonTitle.text = rightButtonStr
        buttonTitle.labelConfig(textAlignment: .center, font: .systemFont(ofSize: 14, weight: .semibold), textColor: color("#FFFFFF"))
        buttonTitle.isUserInteractionEnabled = false
        
        let imageV = UIImageView()
        containerView.addSubview(imageV)
        imageV.snp.makeConstraints { make in
//            make.leading.equalTo(containerView)
            make.trailing.equalTo(buttonTitle.snp.leading).offset(-5)
            make.centerY.equalTo(containerView)
            make.size.equalTo(CGSize(width: 17, height: 17))
        }
        imageV.image = UIImage(named: rightImageName)?.withRenderingMode(.alwaysOriginal)
        imageV.contentMode = .scaleAspectFit
        
        buttonTitle.layoutIfNeeded()
        imageV.layoutIfNeeded()
        containerView.layoutIfNeeded()
        
        containerView.backgroundColor = .green
        
        printLog("查看这个吧:\(containerView.frame)")
        
        let control = UIControl(frame: .init(x: screenWidth-16-(17+5+buttonTitle.frame.size.width), y: statusBarHeight, width: 17+5+buttonTitle.frame.size.width, height: 44))
        control.addTarget(target, action: rightButtonAction, for: .touchUpInside)
        self.view.addSubview(control)

    }
    
    
    
    func changeCustomNavigationBarAlpha(_ alpha: CGFloat) {
        self.customNavigationBar?.alpha = alpha
    }
    
    @objc func empty() {}
}

extension JDBaseViewController {
    //下部弹出控制器
    func showBottomCustomController(viewController : UIViewController, screenHeightRation: Float = 0.6) {
                
        let dataSource = PresetsDataSource()
        var attributes = dataSource[5, 0].attributes
        attributes.positionConstraints.size = .init(
            width: .fill,
            height: .ratio(value: CGFloat(screenHeightRation))
        )
        
        SwiftEntryKit.display(entry: viewController, using: attributes)
    }
}
